package global

import (
	"github.com/gin-gonic/gin"
	"log"
	"reflect"
)

var (
	controllerContainer = make(map[string]any)
	serviceContainer    = make(map[string]any)
	modelContainer      = make(map[string]any)
)

// RegisterModel 注册Model
func RegisterModel(m any) {
	//实例的存储名字
	beanName := reflect.ValueOf(m).Elem().Type().String()
	_, ok := modelContainer[beanName]
	if ok {
		log.Fatalln("该实例名称已存在", beanName)
	}
	modelContainer[beanName] = m
}

// GetModelContainerValueSplice 获取model
func GetModelContainerValueSplice() []any {
	list := make([]any, 0)
	for _, val := range modelContainer {
		list = append(list, val)
	}
	return list
}

// RegisterService 注册Service
func RegisterService(s any) {
	//实例的存储名字
	beanName := reflect.ValueOf(s).Elem().Type().String()
	_, ok := serviceContainer[beanName]
	if ok {
		log.Fatalln("该实例名称已存在", beanName)
	}
	serviceContainer[beanName] = s
}

// GetService 获取服务
func GetService(s any) any {
	beanName := reflect.ValueOf(s).Type().String()
	bean := serviceContainer[beanName]
	return bean
}

// RegisterController 注册Controller
func RegisterController(c any) {
	//实例的存储名字
	beanName := reflect.ValueOf(c).Elem().Type().String()
	_, ok := controllerContainer[beanName]
	if ok {
		log.Fatalln("该实例名称已存在", beanName)
	}
	controllerContainer[beanName] = c
}

// RegisterRouter 注册路由
func RegisterRouter(engine *gin.RouterGroup) {
	for _, controller := range controllerContainer {
		// 注册
		methodIndex := reflect.ValueOf(controller).MethodByName("RegisterController")
		methodIndex.Call([]reflect.Value{reflect.ValueOf(engine)})
	}
}
